//
//  BRCouponsListViewController.m
//  BrezzeSaaS
//
//  Created by IOS on 2022/1/18.
//  Copyright © 2022 Brezze GWG. All rights reserved.
//

#import "BRCouponsListViewController.h"
#import "BRCouponsBaseCell.h"
#import "YGCategoryView.h"
#import "BRCouponsCenterVC.h"

@interface BRCouponsListViewController ()<QMUITableViewDelegate,QMUITableViewDataSource,QMUITextFieldDelegate>
{
    NSInteger _offset;
    NSMutableArray *_dataList;
    
    QMUIButton *_redeemBtn;
}
@property (nonatomic,assign) NSInteger selIndex;

@property (nonatomic,strong) QMUITextField *codeTf;

@property (nonatomic,strong) YGCategoryCustomView *couponTypeView;

@property (nonatomic,strong) UIView *headBottomView;
@property (nonatomic,strong) UIView *sectionView;
@property (nonatomic,strong) UIView *sectionViewBG;

@end

@implementation BRCouponsListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _dataList = [NSMutableArray array];
   
    self.emptyLYView.contentViewOffset = 30;
    self.netErrorView.contentViewOffset = 30;
    [self setUI];
    
    [self addRefreshActionForView:self.tableView];
    [self addLoadMoreActionForView:self.tableView];
    
    self.tableView.mj_footer.hidden = YES;
    [self requeCouponList];
    
    [self br_blockAction];
}

- (void)handleListRefreshAction {
    _offset = 0;
    [self requeCouponList];
}

- (void)handleListLoadMoreAction {
    _offset += 20;
    [self requeCouponList];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (self.scanTypeIn != 0) {
        [self.couponTypeView itemMove:self.scanTypeIn];
        self.scanTypeIn = 0;
    }
    
    
}

#pragma mark - request --
- (void)requeCouponList {
    
    NSDictionary *dic;
    dic = @{@"offset":@(_offset)};
    NSString *url = [BRAPI myCouponsList];
    if (self.selIndex == 1) {
        url = [BRAPI myPromoList];
    }
    [self.tableView ly_startLoading];
    [[BRRequestManager shared] GET:url params:dic succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        NSLog(@"%@",dataDict);
        if (self->_offset == 0) {
            [self->_dataList removeAllObjects];
        }
        NSInteger allC = self->_dataList.count;
        NSArray *list = [BRCouponModel mj_objectArrayWithKeyValuesArray:dataDict[@"data"]];
        [self->_dataList addObjectsFromArray:list];
        if (self->_dataList.count < allC + kPageSize || self->_dataList.count == 0 ) {
            self.tableView.mj_footer.hidden = YES;
        }
        
        [self.tableView reloadData];
        [self showBREmptyView:self.tableView];
        [self handleEndRefreshForView:self.tableView];
        
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [self showBRErrorView:self.tableView];
        [self handleEndRefreshForView:self.tableView];
        
    }];
}

- (void)requestPromo {
    
    if (self.codeTf.text.length == 0) {
        [BRHud showAuto:Localized(@"coupon_enterPromoCode") inView:self.view];
        return;
    }
    BOOL ican = [BRTools checkIsInviteCode:self.codeTf.text];
    if (!ican) {
        [BRHud showAuto:Localized(@"toast_validPromo") inView:self.view];
        return;
    }
    [BRHud showInView:self.view];
    NSString *bigCode = [self.codeTf.text uppercaseString];//转大写
    NSString *url = [NSString stringWithFormat:@"%@?code=%@",[BRAPI promoCodeRedeem],bigCode];
    [[BRRequestManager shared] POST:url params:@{} succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        
        NSLog(@"code = %@",dataDict[@"data"]);
        [BRHud hiddenInView:self.view];
        [BRHud showAutoSuccInView:self.view];
        
        [self handleListRefreshAction];
        
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [BRHud hiddenInView:self.view];
    }];
    
}

- (void)toCouponCenter {
    // 兑换中心
    BRCouponsCenterVC *vc = [[BRCouponsCenterVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    
    WS(weakSelf);
    vc.redeemSuccBlock = ^{
        [weakSelf handleListRefreshAction];
    };
}

#pragma mark - Action --
- (void)br_blockAction {
    WS(weakSelf);
    self.couponTypeView.itemSeletedBlock = ^(NSInteger index) {
        weakSelf.selIndex = index;
    };
}

- (void)setSelIndex:(NSInteger)selIndex {
    _selIndex = selIndex;
    
    [self handleListRefreshAction];
//    [self.tableView.mj_header beginRefreshing];
}

- (void)pop {
    
    if (self.vcIn == 2) {
        [self.navigationController popToRootViewControllerAnimated:YES];
        return;
    }
    [super pop];
}

#pragma mark - tableView Delegate --

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
  
    return _dataList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    BRCouponModel *dto = _dataList[indexPath.row];
    
    NSString *identifier = [NSString stringWithFormat:@"BRListCouponsCell_%ld_%ld",self.selIndex,dto.userCouponId];
    BRListCouponsCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[BRListCouponsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    cell.dto = dto;
    
//    WS(weakSelf);
    cell.openBlock = ^(BOOL open) {
        if (open) [tableView beginUpdates];
        if (!open) [tableView endUpdates];
        
    };
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    

    
}

#pragma mark - scroller --
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
 
    
//    NSLog(@"%.2f",_headView.mj_h);
    CGFloat offsetY = scrollView.contentOffset.y;
    CGFloat newoffsetY = offsetY;
    CGFloat maxY = 58;
    // 临界值150，向上拖动时变透明
    
    [self br_changSupperView:newoffsetY < maxY];
}

- (void)br_changSupperView:(BOOL)defaultV {
    
    if (defaultV) {
        if (self.headBottomView.subviews.count > 0) return;
        
        [self.headBottomView addSubview:self.couponTypeView];
        
    }else {
        if (self.sectionViewBG.subviews.count > 0) return;
        [self.sectionViewBG addSubview:self.couponTypeView];
        
    }
    self.sectionView.hidden = defaultV;
}

#pragma mark - textField delegate --
- (void)textFieldDidChangeSelection:(UITextField *)textField {
    
    _redeemBtn.enabled = [BRTools checkIsInviteCode:textField.text];
    if (textField.text.length >= 8) {
        
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if ([string isEqualToString:@""]) {
        return YES;
    }
    return [BRTools checkIsNumberABC:string];
}

- (void)valueChange:(QMUITextField *)textF {
    
    if (textF == _codeTf) {
        _redeemBtn.enabled = textF.text.length > 7;
    }
}


#pragma mark - UI --
- (void)setUI {
    
    BRNavView *navV = [self br_createTop:Localized(@"menu_coupon")];
    
    self.tableView.estimatedRowHeight = 134;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = UIColor.clearColor;
    [self.tableView registerClass:[BRListCouponsCell class] forCellReuseIdentifier:@"BRListCouponsCell"];
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.tableView.frame = CGRectMake(0, kSafeAreaTopHeight, kScreenWidth, kScreenHeight - kSafeAreaTopHeight - kSafeAreaBottomHeight - 72);
    
    UIView *head = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 116)];
    self.tableView.tableHeaderView = head;
    UIView *bfoot = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 14)];
    self.tableView.tableFooterView = bfoot;
    
    QMUITextField *codeTf = [[QMUITextField alloc] init];
    codeTf.clearButtonMode = UITextFieldViewModeWhileEditing;
    codeTf.clearButtonPositionAdjustment = UIOffsetMake(-118, 0);
    codeTf.textInsets = UIEdgeInsetsMake(0, 14, 0, 98);
    codeTf.placeholderColor = UIColorMakeWithHex(@"#AAAAAC");
    codeTf.font = [UIFont fontM:14];
    codeTf.textColor = kColorTitle;
    codeTf.tintColor = kColorMain;
    codeTf.placeholder = Localized(@"coupon_enterPromoCode");
//    emailTf.delegate = self;
    [head addSubview:codeTf];
    codeTf.layer.cornerRadius = 7;
    codeTf.layer.masksToBounds = YES;
    codeTf.delegate = self;
    codeTf.backgroundColor = kColorBGEC;
    [codeTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kScreenWidth - 28);
        make.height.mas_equalTo(44);
        make.centerX.offset(0);
        make.top.offset(14);
    }];
    codeTf.maximumTextLength = 8;
    _codeTf = codeTf;
    [codeTf addTarget:self action:@selector(valueChange:) forControlEvents:UIControlEventEditingChanged];
    
    QMUIButton *redeemBtn = [[QMUIButton alloc] init];
    [redeemBtn setTitle:Localized(@"coupon_redeem") forState:UIControlStateNormal];
    [redeemBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [redeemBtn setBackgroundColor:kColorMain];
    redeemBtn.titleLabel.font = [UIFont fontS:12];
    [codeTf addSubview:redeemBtn];
    [redeemBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(44);
        make.width.mas_equalTo(88);
        make.top.right.offset(0);
        
    }];
    [redeemBtn addTarget:self action:@selector(requestPromo) forControlEvents:UIControlEventTouchUpInside];
    redeemBtn.enabled = NO;
    _redeemBtn = redeemBtn;
    
    self.headBottomView = [[UIView alloc] init];
    [head addSubview:self.headBottomView];
    [self.headBottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(58);
        make.bottom.offset(0);
        make.left.right.offset(0);
    }];
    [self.headBottomView addSubview:self.couponTypeView];
    
    self.sectionView = [[UIView alloc] init];
    self.sectionView.hidden = YES;
    self.sectionView.backgroundColor = UIColor.whiteColor;
    [self.sectionView br_addBaseShadowDown];
    [self.view addSubview:self.sectionView];
    [self.sectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(72 + kSafeAreaTopHeight);
        make.top.offset(0);
        make.left.right.offset(0);
    }];
    
    UIView *seactionBG = [[UIView alloc] init];
    [self.sectionView addSubview:seactionBG];
    [seactionBG mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(72);
        make.bottom.offset(0);
        make.left.right.offset(0);
    }];
    _sectionViewBG = seactionBG;
    
    UIView *bView = [[UIView alloc] init];
    bView.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:bView];
    [bView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(72 + kSafeAreaBottomHeight);
        make.bottom.offset(0);
        make.left.right.offset(0);
    }];
    [bView br_addBaseShadow];
    
    QMUIButton *bBtn = [BRToolsView br_btnBGImg:Localized(@"coupon_couponCenter")];
    [bView addSubview:bBtn];
    [bBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(14);
        make.right.offset(-14);
        make.height.mas_equalTo(52);
        make.top.offset(10);
    }];
    
    [bBtn addTarget:self action:@selector(toCouponCenter) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view bringSubviewToFront:navV];
}

- (YGCategoryCustomView *)couponTypeView {
    if (_couponTypeView == nil) {
        _couponTypeView = [[YGCategoryCustomView alloc] initWithFrame:CGRectMake(14, 14, kScreenWidth - 28, 44) titles:@[Localized(@"Order_coupon"),Localized(@"pay_promoCode"),]];
      
    }
    return _couponTypeView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
